package com.mxpio.erp.sales.controller;


import com.mxpio.erp.common.sales.entity.Customer;
import com.mxpio.erp.common.sales.service.CustomerService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.CriteriaUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Api(value = "CustomerController", tags = { "客户数据接口" })
@RestController
@RequestMapping("/erp/sales/cst/")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @GetMapping("list")
    @ApiOperation(value = "客户列表", notes = "获取客户列表（无分页）", httpMethod = "GET")
    public Result<List<Customer>> list(String criteria) throws UnsupportedEncodingException {
        Criteria c = CriteriaUtils.json2Criteria(criteria);
        List<Customer> customers = customerService.list(Customer.class, c);
        return Result.OK(customers);
    }

    @GetMapping("page")
    @ApiOperation(value = "客户列表", notes = "获取客户列表（分页）", httpMethod = "GET")
    public Result<Page<Customer>> page(String criteria, Integer pageSize, Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Criteria c = CriteriaUtils.json2Criteria(criteria);
        Page<Customer> customers = customerService.listPage(Customer.class, page, c);
        return Result.OK(customers);
    }

    @GetMapping("list/{pnCode}")
    @ApiOperation(value = "根据pnCode获取客户", notes = "根据pnCode获取客户", httpMethod = "GET")
    public Result<Customer> getById(@PathVariable(name = "pnCode", required = true) String pnCode) {
        Customer customer = customerService.getById(Customer.class, pnCode);
        return Result.OK(customer);
    }

    @PostMapping("add")
    @ApiOperation(value = "新增客户", notes = "新增客户", httpMethod = "POST")
    public Result<Customer> add(@RequestBody Customer customer) {
        customerService.save(customer);
        return Result.OK(customer);
    }

    @PutMapping("edit")
    @ApiOperation(value = "编辑客户", notes = "编辑客户", httpMethod = "PUT")
    public Result<Customer> edit(@RequestBody Customer customer) {
        customerService.update(customer);
        return Result.OK(customer);
    }

    @DeleteMapping("remove/{pnCodes}")
    @ApiOperation(value = "根据pnCode删除客户", notes = "删除客户", httpMethod = "DELETE")
    public Result<Customer> remove(@PathVariable(name = "pnCodes", required = true) String pnCodes) {
        String[] pnCode = pnCodes.split(",");
        for(String key : pnCode){
            customerService.remove(Customer.class, key);
        }
        return Result.OK();
    }
}
